#！/usr/bin/env python
import codecs

class MenuGenerator:
    """ 用于菜单选项的生成, 仿照optparse"""

    def __init__(self, file_path, annotation="MenuItemDetail"):
        self.file_path = file_path
        self.annotation = annotation
        self.import_dict = {}
        self.options_str = None

    def parse_options(self, args_str=None):
        if not args_str:
            self._read_file()
            args_str = self.options_str

        start_index = 0
        current_key = None
        is_in_quote = False
        if not args_str or len(args_str) == 0:
            return None

        result_dict = {}
        args_len = len(args_str)
        # print("args_len is " + str(args_len))
        while start_index < args_len:
            if not current_key:
                key_end_index = args_str.find('=', start_index, args_len)
                if key_end_index <= 0:
                    break

                current_key = args_str[start_index : key_end_index].strip()
                start_index = key_end_index + 1
                # print("find current key: " + current_key)
            else:
                char = args_str[start_index]
                if char == ' ':
                    start_index += 1
                    continue
                elif char == '"':
                    is_in_quote = True

                if not is_in_quote:
                    key_end_index = args_str.find(',', start_index, args_len)
                    if key_end_index <= 0:
                        raise Exception('check source code')

                    result_dict[current_key] = args_str[start_index : key_end_index].strip()
                    start_index = key_end_index + 1
                else:
                    key_end_index = args_str.find('"', start_index + 1, args_len)
                    if key_end_index <= 0:
                        raise  Exception('check source code')

                    result_dict[current_key] = args_str[start_index : key_end_index + 1].strip()
                    start_index = key_end_index + 2

                current_key = None
                is_in_quote = False

        print("result_dict is: " + str(result_dict))
        return result_dict

    def _read_file(self):
        file = codecs.open(self.file_path, encoding='utf-8')
        is_in_annotation = False
        for line in file:
            line.strip()
            if line.startswith("@" + self.annotation + "("):
                is_in_annotation = True
                self.options_str = line
            elif line.startswith("public class"):
                is_in_annotation = False
                break
            elif is_in_annotation:
                self.options_str += line
            elif line.startswith("import"):
                key = line[line.rfind(".") + 1 : -2]
                value = line[len("import ") : -2]
                self.import_dict[key.strip()] = value.strip()
        if not self.options_str:
            return

        self.options_str.replace('\n', '')
        first = self.options_str.find('(')
        last = self.options_str.rfind(')')
        self.options_str = self.options_str[first + 1: last]
        print("file: " + self.file_path)
        print("options_str is: " + self.options_str)


if __name__ == '__main__':

    import os
    activityPath = '../java/ldk/easytouch/example/activity'
    generateObjectPath = '../java/ldk/easytouch/example/activity/ActivityTotalConstant.java'
    file_list = os.listdir(activityPath)

    menu_array = []
    for file_name in file_list:
        file_name = activityPath + '/' + file_name
        generator = MenuGenerator(file_name)
        options = generator.parse_options()
        if not options:
            continue
        options['activity_name'] = '"' + file_name[len('../java/'):-5].replace('/', '.') + '"'
        if not 'canDelete' in options:
            options['canDelete'] = 'true'
        if not 'settingActivityName' in options:
            options['settingActivityName'] = 'null'
        if not 'settingActivityActionName' in options:
            options['settingActivityActionName'] = 'null'
        menu_array.append(options)
        # print("import file is: " + str(generator.import_dict))


    from tornado import template
    output_file = open(generateObjectPath, 'wb')
    loader = template.Loader("./")
    output_file.write(loader.load("ActivityTotalConstantTemplate").generate(menus=menu_array))
